using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;

public class DroneHandler : MonoBehaviour
{
	public DroneHead Head;

	public Rigidbody Body;

	public float ChangeTargetDist = 1f;

	public float ChangeTargetTime = 10f;

	public Vector3 InitialPos;

	public Vector3 InitialRot;

	public float Strength = 10f;

	public GameObject DepleteFX;

	public GameObject FuelDock;

	public Transform FillAmount;

	private float _drillTime;

	private float _targetTimer;

	private Vector3 _target;

	private MapCreatorEditor _mapCreator;

	private float _initialTime;

	public bool IsDrilling()
	{
		return _drillTime > 0f;
	}

	public void OnGameStarted(int duration)
	{
		DoReset();
		_drillTime = duration;
		StartDrilling();
	}

	public void OnRVTaken()
	{
		_drillTime = 30f;
		StartDrilling();
	}

	public void StartDrilling()
	{
		Body.isKinematic = false;
		Head.enabled = true;
		Head.amount = NintendoPlayerPrefs.GetInt("Power", 0) * 2;
		FindNewTarget();
		_initialTime = _drillTime;
		FillAmount.localScale = Vector3.one;
	}

	public void StopDrilling(bool instant = true)
	{
		Body.isKinematic = true;
		_drillTime = 0f;
		Head.enabled = false;
		if (instant)
		{
			base.transform.position = InitialPos;
			base.transform.eulerAngles = InitialRot;
			DoReset();
		}
		else
		{
			base.transform.DOMove(InitialPos, 0.5f).OnComplete(DoReset);
			base.transform.DORotate(InitialRot, 0.5f);
		}
	}

	public void DoReset()
	{
		_drillTime = 0f;
		base.transform.position = InitialPos;
		base.transform.eulerAngles = InitialRot;
		_target = InitialPos;
		FuelDock.SetActive(value: true);
		FillAmount.transform.localScale = new Vector3(1f, 0f, 1f);
	}

	private void FindNewTarget()
	{
		if (!_mapCreator)
		{
			_mapCreator = Object.FindObjectOfType<MapCreatorEditor>();
		}
		List<Transform> blocks = _mapCreator.Map.Blocks;
		for (int i = 0; i < 10; i++)
		{
			int index = Random.Range(0, blocks.Count);
			if (!blocks[index].GetComponent<Rigidbody>() && blocks[index].transform.position.y > 1f)
			{
				_target = blocks[index].transform.position;
				break;
			}
		}
		_targetTimer = ChangeTargetTime;
	}

	private void FixedUpdate()
	{
		if (!(_drillTime > 0f))
		{
			return;
		}
		_drillTime -= Time.fixedUnscaledDeltaTime;
		_targetTimer -= Time.fixedUnscaledDeltaTime;
		FillAmount.localScale = new Vector3(1f, _drillTime / _initialTime, 1f);
		if (_drillTime <= 0f)
		{
			DepleteFX.SetActive(value: false);
			DepleteFX.SetActive(value: true);
			StopDrilling(instant: false);
			return;
		}
		Vector3 vector = _target - base.transform.position;
		if (vector.magnitude <= ChangeTargetDist || _targetTimer <= 0f)
		{
			FindNewTarget();
			vector = _target - base.transform.position;
			if (vector.magnitude <= ChangeTargetDist)
			{
				return;
			}
		}
		vector = vector.normalized;
		base.transform.forward = Vector3.Lerp(base.transform.forward, vector, Time.fixedUnscaledDeltaTime);
		Body.AddForce(vector * Strength * Time.fixedUnscaledDeltaTime);
	}
}
